package thread;

import com.sun.xml.internal.stream.util.ThreadLocalBufferAllocator;

import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author mgm
 */
public class ScheduledDemo {

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor scheduledPoolExecutor = new ScheduledThreadPoolExecutor(2, (ThreadFactory) target -> {
            Thread thread = new Thread(target);
            thread.setDaemon(false);
            return thread;
        });

        Runnable printDateTask = () -> {
            final Date date = new Date();
            System.out.println(date + "--------- print task @ " + Thread.currentThread().getId());
            try {
                Thread.sleep(2000);
                System.out.println(date + "#");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Runnable thrownExceptionTask = () ->{
            System.out.println("thrownExceptionTask run");
           throw new RuntimeException("thrownExceptionTask demo");
        };

//        scheduledPoolExecutor.execute(thrownExceptionTask);

//        scheduledPoolExecutor.schedule(printDateTask, 1, TimeUnit.SECONDS);
//        scheduledPoolExecutor.scheduleAtFixedRate(printDateTask, 0,1, TimeUnit.SECONDS);
        scheduledPoolExecutor.scheduleWithFixedDelay(printDateTask, 0,1, TimeUnit.SECONDS);
//        scheduledPoolExecutor.shutdown();
    }
}
